//
// Created by 17775 on 2024/6/21.
//

#include "powerprofile.h"
#include "ui_PowerProfile.h"


PowerProfile::PowerProfile(QWidget *parent) : QDockWidget(parent), ui(new Ui::PowerProfile) {
    ui->setupUi(this);
    setWindowTitle("LiveMode:Power Profile");
    setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);

    customPlot = ui->customPlot;
//    customPlot->setBackground(QBrush(Qt::darkGray));
    customPlot->setBackground(QColor(0, 0, 50));

    customPlot->addGraph();
    customPlot->graph(0)->setPen(QPen(Qt::red));
    customPlot->graph(0)->setName("Power Content");

    QVector<double> x(100), y(100);
    for (int i = 0; i < 100; ++i)
    {
        x[i] = i / 10.0;
        y[i] = 100.0 / (1 + exp(-x[i] + 5));
    }
    customPlot->graph(0)->setData(x, y);

    customPlot->xAxis->setLabel("Diameter [mm]");
    customPlot->yAxis->setLabel("Power Content[%]");
    QPen pen;
    pen.setColor(Qt::white);
    customPlot->xAxis->setBasePen(pen);
    customPlot->yAxis->setBasePen(pen);
    customPlot->xAxis->setTickLabelColor(Qt::white);
    customPlot->xAxis->setLabelColor(Qt::white);
    customPlot->yAxis->setTickLabelColor(Qt::white);
    customPlot->yAxis->setLabelColor(Qt::white);

    customPlot->xAxis->setRange(0, 10);
    customPlot->yAxis->setRange(0, 100);

    title = new QCPTextElement(customPlot, "Power Profile", QFont("sans", 17, QFont::Bold));
    title->setTextColor(Qt::white);
    customPlot->plotLayout()->insertRow(0);
    customPlot->plotLayout()->addElement(0, 0, title);

    customPlot->legend->setVisible(true);

    customPlot->xAxis->grid()->setVisible(false);
    customPlot->yAxis->grid()->setVisible(false);

    customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectAxes);
    customPlot->setNotAntialiasedElements(QCP::aeAll);

    customPlot->setContextMenuPolicy(Qt::CustomContextMenu);
    verticalLine = new QCPItemLine(customPlot);
//    textLabel = new QCPItemText(customPlot);
//    textLabel->setPositionAlignment(Qt::AlignLeft | Qt::AlignVCenter); // 文本左对齐，垂直居中
//    textLabel->position->setParentAnchor(verticalLine->end); // 将文本锚定到垂直线的终点
//    textLabel->position->setCoords(0, 0);  // 微调位置
//    textLabel->setFont(QFont("Arial", 10)); // 设置字体
//    textLabel->setColor(Qt::yellow); // 设置文本颜色
//    textLabel->setText("d = 1.00\npc = 0.06"); // 设置两行文本内容

    connect(customPlot, &QCustomPlot::customContextMenuRequested, this, [=](const QPoint& point) {
        if(m_contextMenu == nullptr) {
            m_contextMenu = new QMenu(this);
            auto m_rescaleAction = new QAction("Zoom to View", this);
            auto m_settingAction = new QAction("Settings", this);
            m_contextMenu->addAction(m_rescaleAction);
            m_contextMenu->addAction(m_settingAction);
            connect(m_rescaleAction, &QAction::triggered, this, [=]() {
                customPlot->rescaleAxes(true);
            });
            connect(m_settingAction, &QAction::triggered, this, [=]() {
                emit showPowerProfileSettings();
            });
        }
        m_contextMenu->exec(QCursor::pos());
    });
    customPlot->replot(QCustomPlot::rpQueuedReplot);
}

void PowerProfile::setTitle(double d, double pc) {
    customPlot->graph(0)->setName(QString("d = %1 pc = %2").arg(d).arg(pc));
}

void PowerProfile::setWindowTitleName(const QString& name) {
    setWindowTitle("LiveMode:Power Profile -" + name);
}

void PowerProfile::receiveMessage(const std::shared_ptr<PowerProfileData<std::vector<float>>> &data) {
    auto diameter = convertVectorToQList(data->diameterData());
    auto power = convertVectorToQList(data->powerData());
    customPlot->graph(0)->setData(diameter, power);
    if(firstRescale) {
        customPlot->rescaleAxes(true);
        firstRescale = false;
    }
    customPlot->replot(QCustomPlot::rpQueuedReplot);
}

void PowerProfile::refreshViewRange() {
    customPlot->rescaleAxes(true);
}

void PowerProfile::setCursorPos(double pos) {
    cursorPos = pos;
    if (cursorPos != preCursorPos) {
        preCursorPos = cursorPos;
        verticalLine->start->setCoords(cursorPos, customPlot->yAxis->range().lower);
        verticalLine->end->setCoords(cursorPos, customPlot->yAxis->range().upper);
    }
}

void PowerProfile::refreshCustomPlot() {
    customPlot->replot(QCustomPlot::rpQueuedReplot);
}

void PowerProfile::setCursorPosition(double pos) {
    verticalLine->start->setCoords(pos, customPlot->yAxis->range().lower);
    verticalLine->end->setCoords(pos, customPlot->yAxis->range().upper);
    QPen pen;
    pen.setColor(Qt::yellow);
    pen.setStyle(Qt::DashLine);
    pen.setWidth(2);
    verticalLine->setPen(pen);
    customPlot->replot(QCustomPlot::rpQueuedReplot);
}

void PowerProfile::changeXUnit(const QString& unit) {
    customPlot->xAxis->setLabel(QString("Diameter [%1]").arg(unit));
    customPlot->rescaleAxes(true);
}

void PowerProfile::showAbscissa(bool show) {
    customPlot->xAxis->grid()->setVisible(show);
}

void PowerProfile::showOrdinate(bool show) {
    customPlot->yAxis->grid()->setVisible(show);
}

QList<double> PowerProfile::convertVectorToQList(const std::vector<float>& vec) {
    QList<double> qList(vec.size());
    std::transform(vec.begin(), vec.end(), qList.begin(), [](float value) {
        return static_cast<double>(value);
    });
    return qList;
}

void PowerProfile::closeEvent(QCloseEvent *event) {
    emit stopNewPowerProfileThread();
    event->accept();
}

void PowerProfile::closePowerProfile() {
    this->close();
}

PowerProfile::~PowerProfile() {
    delete ui;
}
